package com.sntk.registermanager.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @ClassName: FileUtil
 * @author: wgchao
 * @createTime: 2019/9/16 4:14 PM
 * @Description: 文件操作工具类
 */
public class FileUtil {
    public final static String TARGETPATH = "E:\\work1\\image";
   // public final static String TARGETPATH = "/Users/wgchao/data";
    /**
     * 文件写入
     * @param srcFile 源文件
     * @param targetName 文件名称
     * @return 返回保存后的文件名
     * @throws Exception
     */
    public static String copyFile(File srcFile, String targetName) throws Exception {
        File target = new File(TARGETPATH);
        //判断目标路径是否是目录
        if (!target.isDirectory()) {
            throw new Exception("文件路径不存在！");
        }

        // 判断是否存在相同的文件名的文件
        File[] listFiles = target.listFiles();
        for (File file : listFiles) {
            if(targetName.equals(file.getName())){
                return targetName += "_01";
            }
        }

        String fileName = srcFile.getName();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        String newFileName = TARGETPATH + File.separator + targetName + suffixName;
        File targetFile = new File(newFileName);
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(targetFile);
            //从in中批量读取字节，放入到buf这个字节数组中，
            // 从第0个位置开始放，最多放buf.length个 返回的是读到的字节的个数
            byte[] buf = new byte[8 * 1024];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                if(in != null){
                    in.close();
                }
            }catch(Exception e){
                System.out.println("关闭输入流错误！");
            }
            try{
                if(out != null){
                    out.close();
                }
            }catch(Exception e){
                System.out.println("关闭输出流错误！");
            }
        }
        return targetName + suffixName;

    }

    /**
     * 删除文件
     * @param fileName 文件名包含后缀
     * @return
     * @throws Exception
     */
    public static boolean deleteFile(String fileName) throws Exception {
        String allFileName = TARGETPATH + File.separator + fileName;
        File file = new File(allFileName);
        if(file.exists()){
            if(file.isFile()){
                return file.delete();
            }
        }
        return false;
    }

}
